package com.esm.sm800.util;

import android.content.Context;
import android.widget.Toast;

import java.io.IOException;
import java.security.InvalidParameterException;

import android_serialport_api.ComBean;
import android_serialport_api.SerialHelper;

//机台相关指令发送
/*
开仓门
回收针
出针
 */
public class JtComm {

    private static final String TAG = JtComm.class.getSimpleName();

    private SerialControl m_SerialPort;

    private static JtComm jtcomm;

    private Context mContext;
    int m_nConnected = 0;

    public static void init(Context context) {
        if (jtcomm == null) {
            jtcomm = new JtComm(context);
        }
    }

    public static JtComm getInstance() {
        return jtcomm;
    }

    public JtComm(Context context) {
        mContext = context;

        String szDevice = "/dev/ttyS3";
        int baudrate = 115200;

        m_SerialPort = new SerialControl();
        m_SerialPort.setPort(szDevice);
        m_SerialPort.setBaudRate(baudrate);
        try {
            m_SerialPort.open();
        } catch (SecurityException e) {
            Toast.makeText(mContext, "Open ttyUART device failed!", Toast.LENGTH_SHORT).show();
            return;
        } catch (IOException e) {
            Toast.makeText(mContext, "Open ttyUART device failed!", Toast.LENGTH_SHORT).show();
            return;
        } catch (InvalidParameterException e) {
            Toast.makeText(mContext, "Open ttyUART device failed!", Toast.LENGTH_SHORT).show();
            return;
        }
        m_nConnected = 1;
    }

    public boolean CloseComm() {
        if (m_nConnected == 1) {  // tty uart mode
            m_SerialPort.stopSend();
            m_SerialPort.close();
        }
        m_nConnected = 0;
        return true;
    }

    //发送开仓门指令
    public boolean sendCommand_opendoor(int pos) {
        if (m_nConnected == 0) {
            return false;
        }
        byte[] bytes = {0x01, 0x02, 0x03, 0x04};
        m_SerialPort.send(bytes, bytes.length);
        return true;
    }

    //回收针
    public boolean sendCommand_hsz() {
        if (m_nConnected == 0) {
            return false;
        }
        byte[] bytes = {0x01, 0x02, 0x03, 0x04};
        m_SerialPort.send(bytes, bytes.length);
        return true;
    }

    //出针
    public boolean sendCommand_chuzhen() {
        if (m_nConnected == 0) {
            return false;
        }
        byte[] bytes = {0x01, 0x02, 0x03, 0x04};
        m_SerialPort.send(bytes, bytes.length);
        return true;
    }

    // uart control classes ======================================================
    private class SerialControl extends SerialHelper {

        public SerialControl() {
        }

        @Override
        protected void onDataReceived(final ComBean ComRecData) {
            //读到的串口数据
        }
    }

}
